#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <pthread.h>

int main(int argc,char *argv[])
{
	int shm_id1,shm_id2;
	char * shm = "a", * shm1 = "b";
	char *buf;
	pid_t pid;
	pthread_mutex_t *mutex;
	pthread_mutexattr_t mutexattr;
	//创建、打开共享内存1
	shm_id1 = shm_open(shm,O_RDWR|O_CREAT,0744);
	//调整内存空间大小
	ftruncate(shm_id1,100);
	//映射共享内存到互斥量
	mutex = (pthread_mutex_t *)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id1,0);
 
	pthread_mutexattr_init(&mutexattr);//互斥量属性初始化
#ifdef _POSIX_THREAD_PROCESS_SHARED
	pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);//互斥量进程共享属性设置
#endif
	pthread_mutex_init(mutex,&mutexattr);//互斥量初始化
	//创建、打开共享内存2
	shm_id2 = shm_open(shm1,O_RDWR|O_CREAT,0744);
	//调整内存空间大小
	ftruncate(shm_id2,100);
	//映射共享内存
	buf = (char *)mmap(NULL,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id2,0);
	
	//fork()创建新进程
	pid = fork();
	if(pid==0)
	{	
		sleep(1);
		printf("I am child process\n");
		pthread_mutex_lock(mutex);
		memcpy(buf,"Hello World!",12);
		printf("child process:  buf value is %s\n",buf);		
		pthread_mutex_unlock(mutex);
	}
	if(pid>0)
	{
	
		pthread_mutex_lock(mutex);
		printf("I am parent process\n");
		memcpy(buf,"I Love China!",13);
		sleep(2);
		printf("parent process: buf value is %s\n",buf);
		pthread_mutex_unlock(mutex);
	}
	pthread_mutexattr_destroy(&mutexattr);//互斥量属性销毁
	pthread_mutex_destroy(mutex);//互斥量销毁
	munmap(mutex,100);//解除虚拟内存映射
	shm_unlink(shm);//释放共享内存
	munmap(buf,100);
	shm_unlink(shm1);
}
